package mts.gui;

import java.awt.Dimension;
import java.awt.Font;
import java.awt.Insets;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JPanel;

import mts.constants.Direction;
import mts.groupdispatcher.FloorRequest;
import mts.groupdispatcher.GroupDispatcher;
import mts.utils.FloorUtil;

import org.apache.log4j.Logger;

public class FloorPanel extends JPanel {

	private static final long serialVersionUID = 134152758239519681L;
	
	private Logger log = Logger.getLogger(FloorPanel.class);
	
	public static final int HAS_UP = 1;
	public static final int HAS_DOWN = 2;
	public static final int HAS_BOTH = 3;

	private MainGui gui;
	
	public FloorPanel(MainGui gui, byte floor) {
		this(gui, floor, HAS_BOTH);
	}
	/**
	 * @param gui
	 * @param floor
	 * @param buttons - Acceptable values 1 = Up, 2 = Down, 3 = UP & DOWN
	 */
	public FloorPanel(MainGui gui, byte floor, int buttons) {
		this.gui = gui;
		
		Label floorLbl = new Label("Floor: " + FloorUtil.getFloorName(floor));
		floorLbl.setPreferredSize(new Dimension(70, 10));
		add(floorLbl);
		
		
		if ((buttons & HAS_UP) == HAS_UP) {
			DirectionButton upBtn = new DirectionButton(floor, Direction.UP);			
			upBtn.setAlignmentX(LEFT_ALIGNMENT);
			add(upBtn);
			
		} else {
			JPanel spacer = new JPanel();
			spacer.setPreferredSize(new Dimension(21, 18));
			add(spacer);// for spacing
		}
		
		if ((buttons & HAS_DOWN) == HAS_DOWN) {
			DirectionButton downBtn = new DirectionButton(floor,Direction.DOWN);
			downBtn.setAlignmentX(RIGHT_ALIGNMENT);
			add(downBtn);
		} else {
			JPanel spacer = new JPanel();
			spacer.setPreferredSize(new Dimension(22, 18));
			add(spacer);// for spacing
		}
		
	}
	
	private class DirectionButton extends JButton {
		
		private static final long serialVersionUID = 26889788523634471L;
		
		public DirectionButton(byte floor, Direction direction)  {
			super(direction.toString());
			
			addActionListener(new ElevatorListener(floor, direction));
			Insets insets = new Insets(0, 1, 0, 1);
			setMargin(insets);
			
			Font f = getFont();
			setFont(new Font(f.getName(), f.getStyle(), 9));
			
		}
	}
	
	private class ElevatorListener implements ActionListener {

		private byte floor;
		private Direction direction;
		public ElevatorListener(byte floor, Direction direction) {
			this.floor = floor;
			this.direction = direction;
		}
		
		@Override
		public void actionPerformed(ActionEvent arg0) {
			log.info("Floor Button [floor:" + FloorUtil.getFloorName(floor) + ", direction: " + direction.toString() + "] was pressed");

			GroupDispatcher groupDispatcher = gui.getGroupDispatcher();
			groupDispatcher.addFloorRequest(new FloorRequest(floor, direction));
			
		}
		
	}
}
